import CryptoJS from "crypto-js";

const SECRET_KEY = process.env.NEXT_PUBLIC_UserInfo_SECRET_KEY; // 建议放在.env中

export const encryptData = (data: any): string | null => {
  if (!SECRET_KEY) {
    console.error("Encryption failed: Secret key is not defined.");
    return null;
  }
  return CryptoJS.AES.encrypt(JSON.stringify(data), SECRET_KEY).toString();
};

export const decryptData = (cipherText: string): any | null => {
  if (!SECRET_KEY) {
    console.error("Decryption failed: Secret key is not defined.");
    return null;
  }
  try {
    const bytes = CryptoJS.AES.decrypt(cipherText, SECRET_KEY);
    const originalText = bytes.toString(CryptoJS.enc.Utf8);
    return originalText ? JSON.parse(originalText) : null;
  } catch (e) {
    console.error("Decryption failed", e);
    return null;
  }
};
